<template>
	<view class="content">
		
				<!-- <van-button @click="addSign" type="info">新建签到任务</van-button> -->
				<view class="">
					<van-notice-bar
					  left-icon="volume-o"
					  text="请将手机靠近nfc标签。"
					/>
					<van-row>
						<van-col span="2">
							<view class="" style="height: 1px;">

							</view>
						</van-col>
						<van-col span="20">
							<van-image width="100%" :height="imageHeight"
								src="cloud://cu4oral6-9g3l2orjbb347b4c.6375-cu4oral6-9g3l2orjbb347b4c-1307874055/签到按钮.png" />
						</van-col>
						<van-col span="2">
							<view class="" style="height: 1px;">

							</view>
						</van-col>
					</van-row>


					<van-button round @click="nfcEnvironment()"
						:custom-style="`width:25%;height:${btnHeight}px;position: relative;top: -418rpx;left: 284rpx`"
						color="linear-gradient(to right, #4bb0ff, #6149f6)">
						签到
					</van-button>
				</view>
				
				<!-- <van-button @click="sacnCode()">
					扫码
				</van-button>
				{{aid}} -->
			
		
		<van-dialog id="van-dialog" />
		
		
		<!-- 轻提示 -->
		<van-toast id="van-toast" />
	</view>
</template>

<script>
	import Toast from '../../wxcomponents/vant/toast/toast';
	import Dialog from '../../wxcomponents/vant/dialog/dialog';
	export default {
		data() {
			return {
				imageHeight: "",
				btnHeight: "",
				aid:""
			}
		},
		onLoad() {
			//检查登录状态
			this.checkLogin();
			//更新token
			// this.aginLogin();
		},
		methods: {
			cloak(aid,guestbook){
				uni.request({
				    url: this.apiurl + '/clock/clock', //仅为示例，并非真实接口地址。
				    data: {
				        labelId:aid,
						guestbook:guestbook
				    },
					method:'PUT',
				    header: {
				        'Authorization': uni.getStorageSync('token') //自定义请求头信息
				    },
				    success: (res) => {
				        console.log(res.data);
						if(res.data.status == 0)
				        Dialog.alert({
				          message: res.data.message,
				        }).then(() => {
				          // on close
				        });
						
				    }
				});
			},
			sacnCode(){
				// 只允许通过相机扫码
				uni.scanCode({
				    onlyFromCamera: true,
					// scanType: ['barCode'],
				    success:  (res) => {
				        console.log('条码类型：' + res.scanType);
				        console.log('条码内容：' + res.result);
						this.aid = res.result;
						this.cloak(this.aid,'扫码打卡')
				    }
				});
			},
			addSign() {
				uni.navigateTo({
					url: '/pages/addSign/addSign'
				});
			},
			image_height() {
				uni.getSystemInfo({
					success: (res) => {
						console.log(res.windowWidth * 0.8)
						this.imageHeight = res.windowWidth * 0.8
						this.btnHeight = res.windowWidth * 0.25
					}
				})
			},
			
			
			
			//重写nfc接口调用
			//检测nfc环境
			nfcEnvironment(){
				//1.调用适配器
				const NFCAdapter = wx.getNFCAdapter();
				//2.监听贴卡
				NFCAdapter.startDiscovery({
					success:res=>{
						console.log('成功'+res)
						Toast.success('请将手机靠近标签');
						this.nfcStart();
					},fail:err=>{
						console.log(err)
						
						if(err.errCode==13001){
							//系统nfc开关未打开
							//Toast.fail('系统nfc开关未打开');
							Dialog.alert({
							  message: '系统nfc开关未打开',
							}).then(() => {
							  // on close
							});
						}else if(err.errCode == 13000){
							//设备不支持
							//Toast.fail('设备不支持');
							Dialog.alert({
							  message: '设备不支持nfc,请扫码签到',
							  showCancelButton:"true"
							}).then(() => {
							  // on close
							  this.sacnCode()
							}).catch(()=>{
								
							});
						}else if(err.errCode == 13021){
							
							this.nfcStart();
						}else{
							// Toast.fail(err.errMsg);
							Dialog.alert({
							  // message: '未知设备问题，请扫码签到'+err.errMsg,
							  message: '未知设备问题，是否打开扫码签到',
							  showCancelButton:"true"
							}).then(() => {
							  // on close
							  this.sacnCode()
							}).catch(()=>{
								
							});
						}
					}
				})
			},
			
			//贴卡收集信息
			nfcStart(){
				console.log("启动监听")
				//字符转义
				/**
				 * 字节对象转字符串
				 * @param {Object} arr
				 */
				const byteToString = function(arr) {
					if (typeof arr === 'string') {
						return arr;
					}
				
					var str = '',
						_arr = arr;
				
					for (var i = 0; i < _arr.length; i++) {
						var one = _arr[i].toString(2),
							v = one.match(/^1+?(?=0)/);
				
						if (v && one.length == 8) {
							var bytesLength = v[0].length;
				
							var store = _arr[i].toString(2).slice(7 - bytesLength);
				
							for (var st = 1; st < bytesLength; st++) {
								store += _arr[st + i].toString(2).slice(2);
							}
				
							str += String.fromCharCode(parseInt(store, 2));
				
							i += bytesLength - 1;
						} else {
							str += String.fromCharCode(_arr[i]);
						}
					}
					return str;
				};
				
				/**
				 * 字符串转字节
				 * @param {Object} str
				 */
				const string2ArrayBuffer = function(str) {
					// 首先将字符串转为16进制
					let val = '';
					for (let i = 0; i < str.length; i++) {
						if (val === '') {
							val = str.charCodeAt(i).toString(16);
						} else {
							val += ',' + str.charCodeAt(i).toString(16);
						}
					}
					// 将16进制转化为ArrayBuffer
					return new Uint8Array(
						val.match(/[\da-f]{2}/gi).map(function(h) {
							return parseInt(h, 16);
						})
					).buffer;
				};
				/**
				 * 格式化得到aid值
				 * @param {Object} buffer
				 */
				const ab2hex = function(buffer) {
					var hexArr = Array.prototype.map.call(
						new Uint8Array(buffer),
				
						function(bit) {
							return ('00' + bit.toString(16)).slice(-2);
						}
					);
					return hexArr.join('');
				};
				
				//1.调用适配器
				const NFCAdapter = wx.getNFCAdapter();
				//2.
				NFCAdapter.onDiscovered(res => {
					console.log("贴卡监听回调")
					console.log(res)
					let aid = parseInt(ab2hex(res.id), 16);
					console.log(aid);
					this.aid = aid;
					this.cloak(aid,'nfc打卡')
					NFCAdapter.stopDiscovery({
						success:res=>{
							console.log('成功结束'+res)
						},fail:err=>{
							console.log('异常结束'+err)
						}
					})
				});
			},
			
			//是否有签到任务
			async ifCloak(){
				uni.request({
					url: this.apiurl + '/sign/user_task', //仅为示例，并非真实接口地址。
					header: {
						'Authorization': uni.getStorageSync('token') //自定义请求头信息
					},
					data: {
						pageNum: 1,
						pageSize: 20
					},
					success: (res) => {
						console.log(res.data)
						
						if(res.data.list.length)
						this.nfcEnvironment();
						return false;
					}
					
				});
				// if(!Array.length(signs.list)){
				// 	console.log(signs.list)
				// 	return false;
				// }
				// console.log(signs.list)
			}

		},
		computed: {

		},
		created() {
			this.image_height();
			
		},
		mounted() {
			this.ifCloak()
			// this.nfcEnvironment()
			
		}
	}
</script>

<style>
	/* .content {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
	} */

	.logo {
		height: 200rpx;
		width: 200rpx;
		margin-top: 200rpx;
		margin-left: auto;
		margin-right: auto;
		margin-bottom: 50rpx;
	}

	.text-area {
		display: flex;
		justify-content: center;
	}

	.title {
		font-size: 36rpx;
		color: #8f8f94;
	}

	.btnStyle {}

	.fontStyle {

		font-family: Arial, Helvetica, sans-serif;
		font-size: 1em;
		vertical-align: middle;
		font-weight: normal
	}
</style>
